package com.allqj.sfx.ddd.member.infrastructure.repository;

import com.allqj.sfx.ddd.member.domain.entity.flow.FlowTaskDef;
import com.allqj.sfx.ddd.member.domain.repository.FlowTaskDefRepository;
import com.allqj.sfx.ddd.member.infrastructure.converter.FlowTaskDefConverter;
import com.allqj.sfx.ddd.member.infrastructure.dao.FlowTaskDefDAO;
import com.allqj.sfx.ddd.member.infrastructure.po.FlowTaskDefDO;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author sjw
 * @className FlowTaskDefRepositoryImpl
 * @date 2022/7/21 9:36
 * @description: FlowTaskDefRepository 具体实现
 * Repository接口定义位于domain层
 * Repository接口具体实现位于infrastructure层
 * 与底层db解耦
 */
@Repository
public class FlowTaskDefRepositoryImpl implements FlowTaskDefRepository {

    private final FlowTaskDefDAO dao;

    public FlowTaskDefRepositoryImpl(FlowTaskDefDAO dao) {
        this.dao = dao;
    }

    @Override
    @Transactional
    public FlowTaskDef save(FlowTaskDef flowTaskDef) {
        if (flowTaskDef == null)
            return null;
        FlowTaskDefDO flowTaskDefDO = FlowTaskDefConverter.INSTANCE.entity2Do(flowTaskDef);
        flowTaskDefDO = dao.save(flowTaskDefDO);
        flowTaskDef.setId(flowTaskDefDO.getId());
        return flowTaskDef;
    }

    @Override
    @Transactional
    public List<FlowTaskDef> save(List<FlowTaskDef> flowTaskDefs) {
        if (flowTaskDefs == null) return null;
        return flowTaskDefs.stream().map(this::save).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public Integer deleteByFlowDef(Integer flowDefId) {
        return dao.deleteByFlowDefId(flowDefId);
    }

    @Override
    public List<FlowTaskDef> taskDefs(Integer flowDefId) {
        if (flowDefId == null) return null;
        List<FlowTaskDefDO> flowTaskDefDOs = dao.findAllByFlowDefIdAndIsdeleteFalse(flowDefId);
        return flowTaskDefDOs.stream().map(FlowTaskDefConverter.INSTANCE::do2Entity).collect(Collectors.toList());
    }
}
